#include "stdafx.h"
#include "ZMutexFactory.h"
#include <QMutexLocker>



CHBMutexFactoryAutoLocker::CHBMutexFactoryAutoLocker( CHBMutexFactory& mutexFactory, const QString& sMutexName )
	: m_mutexFactory(mutexFactory)
{
	m_sMutexName = sMutexName;
	m_mutexFactory.Lock(m_sMutexName);
}

CHBMutexFactoryAutoLocker::~CHBMutexFactoryAutoLocker()
{
	m_mutexFactory.UnLock(m_sMutexName);
}
//////////////////////////////////////////////////////////////////////////
CHBMutexFactory::CHBMutexFactory(void)
{
}

CHBMutexFactory::~CHBMutexFactory(void)
{
}

void CHBMutexFactory::Lock( const QString& sMutexName )
{
	_getMutexPtr(sMutexName)->lock();
}

void CHBMutexFactory::UnLock( const QString& sMutexName )
{
	_getMutexPtr(sMutexName)->unlock();
}

QMutex* CHBMutexFactory::_getMutexPtr( const QString& sMutexName )
{
	QMutexLocker locker(&m_mutex);
	auto it = m_mutexMap.find(sMutexName);
	if (it == m_mutexMap.end())
	{
		QMutex* pMutex = new QMutex();
		m_mutexMap.insert(std::map<QString, QMutex*>::value_type(sMutexName, pMutex));
		return pMutex;
	}
	else
	{
		return it->second;
	}
}
//////////////////////////////////////////////////////////////////////////
QMutex CHBMutexFactorySingleton::m_mutex;
CHBMutexFactorySingleton::CHBMutexFactorySingleton()
{

}

CHBMutexFactorySingleton::~CHBMutexFactorySingleton()
{
	delete (&CHBMutexFactorySingleton::instance());
}

CHBMutexFactorySingleton& CHBMutexFactorySingleton::instance()
{
	static CHBMutexFactorySingleton* pMutexFactorySingleton = 0;
	if (0 == pMutexFactorySingleton)
	{
		QMutexLocker locker(&m_mutex);
		if (0 == pMutexFactorySingleton)
		{
			pMutexFactorySingleton = new CHBMutexFactorySingleton;
		}
	}

	return (*pMutexFactorySingleton);
}